package com.camera.yl.v.models

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.alibaba.android.arouter.launcher.ARouter
import com.camera.base.Log.YLogImpl
import com.camera.base.util.FileUtil
import com.camera.base.v.models.BaseViewModel
import com.camera.base.v.models.SystemNavBarViewModel
import com.camera.routemodule.RouterPath
import com.camera.yl.R
import com.camera.yl.v.data.GalleryList
import com.camera.yl.manager.UploadManager
import com.camera.yl.models.UploadInfo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.io.File
import javax.inject.Inject

@HiltViewModel
class FileViewModel @Inject constructor(var systemNavBarViewModel: SystemNavBarViewModel?) :
    BaseViewModel() {
        val TAG = FileViewModel::class.java.simpleName
        var isDirectoryVideo = true;
        var isDirectoryAudio = true;
        
        // 当前激活的tab类型
        private var currentTabType: Int = -1
        
        // 选择模式相关状态
        private val _isSelectionMode = MutableStateFlow(false)
        val isSelectionMode: StateFlow<Boolean> = _isSelectionMode
        
        private val _selectedFiles = MutableStateFlow<Set<File>>(emptySet())
        val selectedFiles: StateFlow<Set<File>> = _selectedFiles
        
        private val _showUploadPanel = MutableLiveData<Boolean>()
        val showUploadPanel: LiveData<Boolean> get() = _showUploadPanel
        
        private val _isSelectAll = MutableStateFlow(false)
        val isSelectAll: StateFlow<Boolean> = _isSelectAll
        
        // 标题栏控制相关状态 - 只保留必要的
        private val _rightText = MutableLiveData<String>()
        val rightText: LiveData<String> get() = _rightText
        
        private val _rightTextVisibility = MutableLiveData<Boolean>()
        val rightTextVisibility: LiveData<Boolean> get() = _rightTextVisibility
        
        // 上传文件事件
        private val _uploadFilesEvent = MutableLiveData<List<String>>()
        val uploadFilesEvent: LiveData<List<String>> get() = _uploadFilesEvent
        
        private val _fileVideoList = MutableStateFlow<List<File>?>(null)
        val fileVideoList: StateFlow<List<File>?>  = _fileVideoList
        private val _fileAudioList = MutableStateFlow<List<File>?>(null)
        val fileAudioList: StateFlow<List<File>?>  = _fileAudioList
        private val _showGallery = MutableLiveData<GalleryList>()
        val showGallery: LiveData<GalleryList> get() = _showGallery
        
        init {
            YLogImpl.e(TAG, "init")
            // 初始化标题栏状态
            _rightTextVisibility.value = false
        }

    /**
     * 设置当前激活的tab
     */
    fun setCurrentTab(type: Int) {
        currentTabType = type
    }
    
    /**
     * 获取当前tab的文件列表
     */
    private fun getCurrentFileList(): List<File>? {
        return when(currentTabType) {
            0 -> _fileVideoList.value
            1 -> _fileAudioList.value
            else -> null
        }
    }

    /**
     * 进入选择模式
     */
    fun enterSelectionMode() {
        _isSelectionMode.value = true
        _showUploadPanel.value = true
        updateTitleBarState()
    }
    
    /**
     * 退出选择模式
     */
    fun exitSelectionMode() {
        _isSelectionMode.value = false
        _selectedFiles.value = emptySet()
        _showUploadPanel.value = false
        _isSelectAll.value = false
        updateTitleBarState()
    }
    
    /**
     * 更新标题栏状态
     */
    private fun updateTitleBarState() {
        val isSelection = _isSelectionMode.value
        if (isSelection) {
            // 选择模式：显示全选按钮
            _rightText.value = if (_isSelectAll.value) "取消全选" else "全选"
            _rightTextVisibility.value = true
        } else {
            // 正常模式：隐藏全选按钮
            _rightTextVisibility.value = false
        }
    }
    
    /**
     * 标题栏右侧按钮点击事件
     */
    fun onRightButtonClicked() {
        if (_isSelectionMode.value) {
            toggleSelectAll()
        }
    }
    
    /**
     * 标题栏取消按钮点击事件
     */
    fun onCancelButtonClicked() {
        exitSelectionMode()
    }
    
    /**
     * 切换文件选择状态
     */
    fun toggleFileSelection(file: File) {
        val currentSelected = _selectedFiles.value.toMutableSet()
        if (currentSelected.contains(file)) {
            currentSelected.remove(file)
        } else {
            currentSelected.add(file)
        }
        _selectedFiles.value = currentSelected
        
        // 检查是否全选
        getCurrentFileList()?.let { files ->
            val fileList = files.filter { it.isFile }
            _isSelectAll.value = currentSelected.size == fileList.size && fileList.isNotEmpty()
            updateTitleBarState() // 更新标题栏状态
        }
    }
    
    /**
     * 全选/取消全选
     */
    fun toggleSelectAll() {
        getCurrentFileList()?.let { files ->
            val fileList = files.filter { it.isFile }
            if (_isSelectAll.value) {
                // 取消全选
                _selectedFiles.value = emptySet()
                _isSelectAll.value = false
            } else {
                // 全选
                _selectedFiles.value = fileList.toSet()
                _isSelectAll.value = true
            }
            updateTitleBarState() // 更新标题栏状态
        }
    }
    
    /**
     * 检查文件是否被选中
     */
    fun isFileSelected(file: File): Boolean {
        return _selectedFiles.value.contains(file)
    }
    
    /**
     * 获取选中文件数量
     */
    fun getSelectedCount(): Int {
        return _selectedFiles.value.size
    }
    
    /**
     * 上传选中的文件
     */
    fun uploadSelectedFiles() {
        val files = _selectedFiles.value.toList()
        YLogImpl.i(TAG, "开始上传文件，共${files.size}个文件")
        
        if (files.isEmpty()) {
            YLogImpl.w(TAG, "没有选中文件，无法上传")
            return
        }
        
        // 获取文件路径列表
        val filePaths = files.map { it.absolutePath }
        
        // 通过UploadManager开始上传
        // 需要Context，通过Application或其他方式获取
        viewModelScope.launch {
            try {
                // 这里需要获取Context，可能需要修改架构来传递Context
                // 暂时先记录日志，实际启动需要在Activity或Fragment中调用
                YLogImpl.i(TAG, "准备启动上传服务，文件路径: $filePaths")
                
                // 发送上传请求事件给UI层处理
                _uploadFilesEvent.value = filePaths
                
            } catch (e: Exception) {
                YLogImpl.e(TAG, "启动上传异常", e)
            }
        }
        
        // 上传开始后退出选择模式
        exitSelectionMode()
    }

    /**
     * 挂起查询方法
     * @param path String
     * @param type Int
     */
     suspend fun loadDirectories(type: Int) {
            YLogImpl.i(TAG, "loadDirectories:  $type")
            var path:String? = null
            when(type){
                0 ->{
                    path = FileUtil.getBaseVideoPath()
                }
                1 ->{
                    path = FileUtil.getBaseCapturePath()
                }
            }
            flow {
                val directory = File(path)
                if (directory.exists() && directory.isDirectory) {
                    val items = directory.listFiles()?.filter { it.isDirectory }?.sortedByDescending {
                         // 提取文件夹名称中的日期部分
                        YLogImpl.i(TAG,it.absolutePath)
                        val dateLong = it.name.takeIf { name -> name.matches(Regex("\\d{8}")) }?.substring(0,8)?.toLongOrNull() ?: 0L
                        dateLong
                   }?.toList() ?: emptyList()
                   emit(items)
                }
            }.catch {
                // 处理异常，例如文件访问权限错误等
                YLogImpl.e("FileViewModel", "Error getting files: ${it.message}")
            }.collect { fileList ->
                when(type){
                    0 ->{
                        isDirectoryVideo = true
                        _fileVideoList.value = fileList
                        // 切换到目录模式时退出选择模式
                        if (_isSelectionMode.value) {
                            exitSelectionMode()
                        }
                    }
                    1 ->{
                        isDirectoryAudio = true
                        _fileAudioList.value = fileList
                        // 切换到目录模式时退出选择模式
                        if (_isSelectionMode.value) {
                            exitSelectionMode()
                        }
                    }
                }
            }
        }

        fun onItemClicked(item: File,type: Int,position: Int) {
                // 如果在选择模式下，点击切换选择状态
                if (_isSelectionMode.value && item.isFile) {
                    toggleFileSelection(item)
                    return
                }
                
                if (item.isDirectory) {
                    loadFiles(item,type)
                }else{
                    //播放视频
                    if (item.name.endsWith(".mp4")){
                        ARouter.getInstance().build(RouterPath.path.mediaplay_activity).withString("path", item.absolutePath).withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
                    }else if (item.name.endsWith(".jpg")){
                        Log.e(TAG, "onItemClicked: "+item.absolutePath  + " " + position)
                        _showGallery.value = GalleryList(_fileAudioList.value!!,position)
                    }
                }
        }
        
        /**
         * 长按文件项
         */
        fun onItemLongClicked(item: File, type: Int): Boolean {
            // 只有在文件模式（非文件夹模式）下才能进入选择模式
            val isFileMode = when(type) {
                0 -> !isDirectoryVideo
                1 -> !isDirectoryAudio
                else -> false
            }
            
            if (isFileMode && item.isFile) {
                enterSelectionMode()
                toggleFileSelection(item)
                return true
            }
            return false
        }

         private fun loadFiles(directory: File, type: Int) {
             viewModelScope.launch {
                 flow {
                     if (directory.exists() && directory.isDirectory) {
                         val items = directory.listFiles()?.filter { it.isFile }?.sortedByDescending { file ->
                             val regex = Regex("(\\d{8})_(\\d{2})-(\\d{2})-(\\d{2})")
                             val matchResult = regex.find(file.name)
                             matchResult?.value?.replace("_", "")?.replace("-", "")?.toLongOrNull() ?: 0L
                         }?.toList() ?: emptyList()
                         emit(items)
                     }
                 }.collect { fileList ->
                     when(type){
                         0 ->{
                             isDirectoryVideo = false
                             _fileVideoList.value = fileList
                             // 进入文件模式时，如果在选择模式则退出
                             if (_isSelectionMode.value) {
                                 exitSelectionMode()
                             }
                         }
                         1 ->{
                             isDirectoryAudio = false
                             _fileAudioList.value = fileList
                             // 进入文件模式时，如果在选择模式则退出
                             if (_isSelectionMode.value) {
                                 exitSelectionMode()
                             }
                         }
                     }
                 }
             }
        }

        fun onBack(type:Int):Boolean{
            // 如果在选择模式，返回键退出选择模式
            if (_isSelectionMode.value) {
                exitSelectionMode()
                return false
            }
            
            return when(type){
                0 ->{
                    if(!isDirectoryVideo){
                        viewModelScope.launch {
                            loadDirectories(type)
                        }
                        false
                    }else{
                        true
                    }
                }
                1 ->{
                    if(!isDirectoryAudio){
                        viewModelScope.launch {
                            loadDirectories(type)
                        }
                        false
                    }else{
                        true
                    }
                }
                else -> {
                    true
                }
            }
        }

    /**
     * 所以某个文件同目录下所有的路径String列表
     * @param file File
     * @return List<String>
     */
    fun getFilesInParentDirectory(file: File): List<String> {
        val parentDirectory = file.parentFile
        return if (parentDirectory != null && parentDirectory.exists() && parentDirectory.isDirectory) {
            parentDirectory.listFiles()?.map { it.absolutePath } ?: emptyList()
        } else {
            emptyList()
        }
    }
}